﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace AppManager.Web
{
    public static class HtmlExtend
    {
        public static string SubStr(this HtmlHelper helper, object obj, int length = 0)
        {
            if (obj == null || string.IsNullOrEmpty(obj.ToString())) return string.Empty;
            var str = obj.ToString();
            if (str.Length > length && length != 0)
            {
                return str.Substring(0, length);
            }
            return str;
        }

        /// <summary>
        /// 为了方便的输出数据库中用富文本框保存的内容，并其可以支持截取
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="obj"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static IHtmlString CusRaw(this HtmlHelper helper, object obj, int length = 0)
        {
            if (obj == null) return helper.Raw(string.Empty);
            string str = obj.ToString();
            if (string.IsNullOrEmpty(str)) return helper.Raw(string.Empty);
            if (str.Length > length && length != 0)
            {
                str = str.Substring(0, length);
            }
            str = HttpUtility.HtmlDecode(str);
            //作用是使得前台浏览器能将后台返回的字符串解析能html，而不是将其看做是string（这样是不能解析的）这就是Html.Raw方法的作用
            return helper.Raw(str);
        }

        /// <summary>
        /// 返回图片和链接（其实就是拼接了字符串，还有点品味的）
        /// </summary>
        /// <param name="html"></param>
        /// <param name="imgSrc">图片地址比如“~/images/logo.png”</param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <param name="routeValue"></param>
        /// <param name="imgCssStyle"></param>
        /// <returns></returns>
        public static MvcHtmlString ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName = "", string controllerName = "", object routeValue = null, string imgCssStyle = "border-style: none;")
        {
            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);

            if (string.IsNullOrEmpty(imgSrc)) return new MvcHtmlString(string.Empty);

            //创建Image标签
            TagBuilder imgTagBuilder = new TagBuilder("img");
            IDictionary<string, object> imgAttributes = new Dictionary<string, object>();
            string imgUrl = urlHelper.Content(imgSrc ?? "");
            imgAttributes.Add("src", imgUrl);
            imgAttributes.Add("style", imgCssStyle);// 图片默认无边框
            imgTagBuilder.MergeAttributes(imgAttributes);
            string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);

            string linkUrl = urlHelper.Action(actionName, controllerName, routeValue);

            //创建一个a标签，然后包裹Image标签，设置链接
            TagBuilder linkTagBuilder = new TagBuilder("a");
            linkTagBuilder.InnerHtml = img;
            linkTagBuilder.MergeAttribute("href", linkUrl);

            return new MvcHtmlString(linkTagBuilder.ToString(TagRenderMode.Normal));
        }

        public static MvcHtmlString RadioText(
            this HtmlHelper Helper,
            string InputID,
            string value = "",
            string Options = "选项1|选项2|选项..")
        {
            var sb = new StringBuilder();
            sb.AppendFormat("<input type='text' style='display:none;' id='{0}' name='{0}' value='{1}'/>", InputID, value);
            foreach (var it in Options.Split('|'))
            {
                sb.AppendFormat("<a href='#' onclick='return OnRadioText(this)' forHID='{1}' value='{0}' style='color:{2}'>[{0}]</a>&nbsp;",
                    it, InputID, it.Equals(value) ? "red" : "blue");
            }
            return MvcHtmlString.Create(sb.ToString());
        }



        public static MvcHtmlString RadioTextFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            string Options = "选项1|选项2|选项..")
        {
            var inputId = ExpressionHelper.GetExpressionText(expression);
            var meta = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var value = (meta.Model == null) ? string.Empty : meta.Model.ToString();
            //return MvcHtmlString.Create(InputID + Value);
            return RadioText(htmlHelper, inputId, value, Options);
        }

        /// <summary>
        /// 返回<span id="inputid"></span>
        /// </summary>
        public static IHtmlString ValErrorFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            Dictionary<string, string> otherAttribute)
        {
            //控件Id
            var inputId = ExpressionHelper.GetExpressionText(expression);
            var meta = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            //控件的值
            var value = (meta.Model == null) ? string.Empty : meta.Model.ToString();
            return Display(htmlHelper, HtmlType.span, inputId, value, otherAttribute);
        }

        public static IHtmlString HtmlFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            HtmlType type,
            Expression<Func<TModel, TProperty>> expression,
            Dictionary<string, string> otherAttribute)
        {
            //控件Id
            var inputId = ExpressionHelper.GetExpressionText(expression);
            var meta = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            //控件的值
            var value = (meta.Model == null) ? string.Empty : meta.Model.ToString();
            return Display(htmlHelper, type, inputId, value, otherAttribute);
        }
        public static IHtmlString Display(
            this HtmlHelper htmlHelper,
            HtmlType type,
            string inputid, string value = "", Dictionary<string, string> otherAttribute = null)
        {
            StringBuilder sb2 = new StringBuilder();
            string str = string.Empty;
            foreach (var item in otherAttribute)
                sb2.AppendFormat("{0}='{1}' ", item.Key, item.Value);
            StringBuilder sb = new StringBuilder();
            if (type == HtmlType.span)
            {
                sb.AppendFormat("<span id={0} name={0}></span>");
            }
            else if (type == HtmlType.text)
            {
                sb.AppendFormat("<input type='text' id='{0}' name='{0}' value='{1}' {2}/>", inputid, sb2, otherAttribute);
            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }

    public enum HtmlType
    {
        text,
        password,
        email,
        span,
    }
}